package org.jeecg.modules.controller.notify;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.modules.wx.entity.WxAccount;
import org.jeecg.common.modules.wx.service.IWxAccountService;
import org.jeecg.common.util.SHA1;
import org.jeecg.common.util.constants.WxConstants;
import org.jeecg.common.util.tencent.response.IMBaseResponse;
import org.jeecg.modules.service.ApiOrderService;
import org.jeecg.modules.service.AsyncService;
import org.jeecg.modules.service.wx.WeixinService;
import org.jeecg.modules.tencent.TencentCallbackContext;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;

/**
 * @author guoyh
 * @ClassName WxNotifyController
 * @Description
 * @since 2020/8/23 12:38
 **/
@RestController
@RequestMapping("notify")
@Slf4j
public class NotifyController {

    @Resource
    private IWxAccountService wxAccountService;
    @Resource
    private WeixinService weixinService;
    @Resource
    private TencentCallbackContext tencentCallbackContext;
    @Resource
    private ApiOrderService apiOrderService;
    @Resource
    private AsyncService asyncService;


    /**
     * 微信公众号事件通知
     *
     * @param xmlStr
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @param accountId
     * @param request
     * @return
     */
    @RequestMapping(value = "wx/{accountId}")
    public String wxNotify(@RequestBody(required = false) String xmlStr,
                           @RequestParam(value = "signature", required = false) String signature,
                           @RequestParam(value = "timestamp", required = false) String timestamp,
                           @RequestParam(value = "nonce", required = false) String nonce,
                           @RequestParam(value = "echostr", required = false) String echostr,
                           @PathVariable("accountId") String accountId,
                           HttpServletRequest request) {
        log.info("微信回调 有事件发生");
        log.info("微信notify,signature:{},timestamp:{},nonce:{},echostr:{},accountId:{}", signature, timestamp, nonce, echostr, accountId);
        String result = "";
        if (!checkClient(timestamp, nonce, signature, accountId)) {
            log.info("校验签名不通过");
            return result;
        }
        if (RequestMethod.GET.name().equals(request.getMethod())) {
            return echostr;
        } else {
            log.info("微信消息通知,xml内容:{}", xmlStr);
            result = weixinService.parsingMsg(xmlStr, accountId);
            if (result.equals(WxConstants.FORWARD)) {
                try {
                    result = asyncService.sendWxNotify(xmlStr, signature, timestamp, nonce);
                } catch (Exception e) {
                    log.info("转发微信请求异常", e);
                }
            }
            log.info("微信消息通知，响应：{}", result);

            return result;
        }
    }
    /**
     * 微信公众号视频问诊推送事件通知
     *
     * @param openid
     * @param doctorId
     * @param request
     * @return
     */
    @RequestMapping(value = "push")
    public void wxPushNotify(
                           @RequestParam(value = "openid", required = false) String openid,
                           @RequestParam(value = "doctorId", required = false) String doctorId,
                           HttpServletRequest request) {
        log.info("微信服务推送");
        apiOrderService.getPushInfo(openid,doctorId,null,null);
    }


    /**
     * 腾讯IM聊天回调
     *
     * @param sdkAppId
     * @param callBackCommand
     * @param contentType
     * @param clientIP
     * @param optPlatform
     */
    @PostMapping("im")
    public IMBaseResponse imNotify(@RequestParam(value = "SdkAppid", required = false) String sdkAppId,
                                   @RequestParam(value = "CallbackCommand", required = false) String callBackCommand,
                                   @RequestParam(value = "contenttype", required = false) String contentType,
                                   @RequestParam(value = "ClientIP", required = false) String clientIP,
                                   @RequestParam(value = "OptPlatform", required = false) String optPlatform,
                                   @RequestBody(required = false) String body) {
        String uuid = IdUtil.fastUUID();
        try {
            log.info("腾讯IM回调，uuid：{}，appid：{}，command：{}，type：{}，ip：{}，platform：{}，body：{}", uuid, sdkAppId, callBackCommand, contentType, clientIP, optPlatform, body);
            IMBaseResponse response = tencentCallbackContext.execute(sdkAppId, callBackCommand, contentType, clientIP, optPlatform, body);
            log.info("腾讯IM回调，返回：{}", JSONUtil.toJsonStr(response));
            return response;
        } catch (Exception e) {
            log.error("腾讯IM回调异常{}", uuid, e);
            return IMBaseResponse.buildFail(e.getMessage());
        }

    }

    @PostMapping("payNotify")
    public String payNotify(@RequestBody(required = false) String body) throws ParseException {
        log.info("微信支付回调，入参：{}", body);
        String result = apiOrderService.payNotify(body);
        log.info("微信支付回调，返回信息：{}", result);
        return result;
    }

    private boolean checkClient(String timestamp, String nonce, String signature, String accountId) {
        try {
            WxAccount weixinAccount = wxAccountService.getByAccountId(accountId);
            return signature.equals(SHA1.gen(weixinAccount.getToken(), timestamp, nonce));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return false;
    }

    //微信模板接口
    private final String SEND_TEMPLATE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send";
    //模板消息详情跳转URL
    private static String url = "https://www.baidu.com/";



}
